# -*- coding: utf-8 -*-

require File.join(Rails.root, "config", "environment.rb")

namespace :data do
  desc "create test accounts."
  task :add_test_accounts => :rails_env do
    if User.where(:login => "aaron").first
      puts "account 'aaron' already exists."
      return false
    end
    aaron = User.create(:login => "aaron",
                        :nick_name => "あーろん",
                        :password => "monkey",
                        :password_confirmation => "monkey")

    setting = Setting.new(:message_format_type => "plain",
                          :blog_format_type => "markdown")
    setting.user = aaron
    setting.save

    profile = Profile.new(:permissions => "none",
                          :age => 35,
                          :email => "aaron@localhost.local",
                          :comment => "Rails界を代表するテストアカウントです。",
                          :birth_day => "1975/01/01 00:00:00 Z")
    profile.user = aaron
    profile.save
  end

  task :load_config => :rails_env do
    require 'active_record'
    ActiveRecord::Base.configurations = Rails.application.config.database_configuration
    config = ActiveRecord::Base.configurations[Rails.env || 'development']
    ActiveRecord::Base.establish_connection(config)
  end

  desc "create fixtures from DB"
  task :to_fixtures do
    targets = ["User", "Friend", "Profile", "Setting"]
    targets.each do |model_name|
      fixture_file = File.join(Rails.root, "test", "fixtures", "#{model_name.underscore.pluralize}.yml")
      File.open(fixture_file, "w") do |f|
        model_name.constantize.all.each_with_index do |record, idx|
          yaml_rec = record.attributes.to_yaml
          result = ""
          yaml_rec.each_line{|line| result += "  " + line}
          result.gsub!(/\A  ---/, "#{model_name.underscore}_#{idx}:")
          f.puts result
          f.puts "\n"
        end
      end
    end
  end
end